import axios from 'axios';
import { Base64 } from 'js-base64';
import Utils from '@/common/pakjUtils';
import TokenOutDialog from '@/components/TokenOutDialog';
import Config from './config';
import { Dialog } from 'mand-mobile';
import store from '@/store';
var CryptoJS = require('crypto-js');
let serverUrl = Config.baseUrl;
if (Utils.isMiniProgram()) {
  serverUrl = Config.xcxBaseUrl;
}
if (process.env.NODE_ENV === 'production') {
  console.info('发行版，服务器为：', serverUrl);
} else {
  console.info('测试版，服务器为：', serverUrl);
}
const instance = axios.create({
  baseURL: serverUrl,
  responseType: 'text',
  responseEncoding: 'utf8',
  validateStatus: function(status) {
    return status >= 200 && status < 300; // default
  }
});
instance.defaults.headers.post['Content-Type'] = 'text/plain,charset=utf-8';
instance.defaults.headers.common['os'] = Utils.getOSName();
instance.defaults.headers.common['osver'] = Utils.getOSVersion();
instance.defaults.headers.common['ims'] = '123';
instance.defaults.headers.common['userType'] = 'phoneorder';
instance.defaults.headers.common['phone_model'] = Utils.getPhoneModel();
instance.interceptors.request.use(
  config => {
    if (store) {
      if (store.getters) {
        if (!store.getters.getToken) {
          console.log('从本地查询用户信息', store.getters.currentUser); // 不能删除
          config.headers.tk = store.getters.getToken;
        } else {
          config.headers.tk = store.getters.getToken;
        }
      }
    }
    if (config.data) {
      let data = JSON.stringify(config.data);
      let md5 = CryptoJS.MD5(data).toString();
      let base64 = Base64.encode(data);
      config.data = md5 + ',' + base64;
    }
    return config;
  },
  errors => {
    console.error(errors);
    alert(errors);
  }
);
instance.interceptors.response.use(
  response => {
    let data = response.data;
    if (data.code === 'error/500') {
      TokenOutDialog.show('您还没有登录');
      return null;
    }
    let param0 = data.split(',')[0];
    let param1 = data.split(',')[1];
    data = Base64.decode(param1);
    if (CryptoJS.MD5(data).toString() === param0) {
      response.data = JSON.parse(data);
      if (response.data.code === '200001') {
        TokenOutDialog.show(response.data.msg);
        return null;
      }
    } else {
      alert('接口数据校验失败');
      return null;
    }
    return response;
  },
  errors => {
    Dialog.alert({
      title: '错误',
      content: '无法连接到服务器'
    });
  }
);
export default instance;
